from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request

from info import db
from info.models import News, Comment, CommentLike, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blue


@news_blue.route("/<int:news_id>")
@user_login_data
def news_details(news_id):
    user = g.user
    news = News.query.order_by(News.clicks.desc()).limit(10)
    new_list = []
    for news_mode in news:
        new_list.append(news_mode.to_dict())
    detail_news = News.query.get(news_id)
    is_collected = False
    is_followed = False
    if user:
        if detail_news in user.collection_news:
            is_collected = True
    if user:
        if detail_news.user in user.followers:
            is_followed = True
    comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    comment_list = []
    comment_likes = []
    comment_likes_ids = []
    if user:
        comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id).all()
        comment_likes_ids = [comment_like.comment_id for comment_like in comment_likes]
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_list.append(comment_dict)
        comment_dict["is_like"] = False
        if comment.id in comment_likes_ids:
            comment_dict["is_like"] = True
            comment_list.append(comment_dict)
    count = len(comment_list)
    data = {
        "user_info": user.to_dict() if user else None,
        "click_news_list": new_list,
        "news": detail_news.to_dict(),
        "is_collected": is_collected,
        "comments": comment_list,
        "count": count,
        "is_followed": is_followed
    }
    return render_template("news/detail.html", data=data)


@news_blue.route("/news_collect", methods=["GET", "POST"])
@user_login_data
def news_collect():
    user = g.user
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    news = News.query.get(news_id)
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="请先登录")
    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="收藏成功")


@news_blue.route("/news_comment", methods=["GET", "POST"])
@user_login_data
def news_comment():
    user = g.user
    news_id = request.json.get("news_id")
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    if not user:
        return jsonify(errno=RET.OK, errmsg="请先登录")
    news = News.query.get(news_id)
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news.id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id
    db.session.add(comment)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())


@news_blue.route("/comment_like", methods=["GET", "POST"])
@user_login_data
def comment_like():
    user = g.user
    news_id = request.json.get("news_id")
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    if not user:
        return jsonify(errno=RET.OK, errmsg="请先登录")

    comment = Comment.query.get(comment_id)
    if action == "add":
        comment_like = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                CommentLike.comment_id == comment_id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.user_id = user.id
            comment_like.comment_id = comment_id
            db.session.add(comment_like)
            comment.like_count += 1
    else:
        comment_like = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                CommentLike.comment_id == comment_id).first()
        if comment_like:
            comment.like_count -= 1
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="点赞成功")


@news_blue.route("/followed_user", methods=["POST", "GET"])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.LOGINERR, errmsg="当前未登录")
    user_id = request.json.get("user_id")
    action = request.json.get("action")
    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查找失败")
    if not other:
        return jsonify(errno=RET.NODATA, errmsg="数据库未找到当前用户")
    if action == "follow":
        if other in user.followed:
            return jsonify(errno=RET.DATAEXIST, errmsg="已经关注了")
        user.followed.append(other)
    else:
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errno=RET.PARAMERR, errmsg="当前用户未关注")
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")
    data = {
        "other": other.to_dict()
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
